{% extends 'basic/layout/page_basic.html' %}
{% load static %}

<!-- 标题 -->
{% block title %}
    登陆账号管理
{% endblock %}

<!-- CSS -->


<!-- 内容 -->
{% block content %}
    <!-- 内容01：面包屑的导航 -->
    <span class="layui-breadcrumb">
      <a href="/">首页</a>
      <a href="#">登陆权限</a>
      <a><b>用户账号</b></a>
    </span>

    <!-- 内容02：查询区域  -->
    <div class="queryArea" style="margin-top: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="queryStr"><b>查询条件：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="queryStr" id="queryStr" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label" for="status"><b>状态：</b></label>
                    <div class="layui-input-inline">
                        <select name="status" id="status">
                            <option value="0">所有</option>
                            <option value="1">启用</option>
                            <option value="2">禁用</option>
                        </select>
                    </div>
                </div>

                <div class="layui-inline">
                    <button type="button" id="btnQuery" class="layui-btn">
                        <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询
                    </button>
                    <button type="button" id="btnAll" class="layui-btn">
                        <i class="fa fa-bars" aria-hidden="true"></i>&nbsp; 全部
                    </button>
                    <button type="button" id="btnAdd" class="layui-btn">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i>&nbsp; 添加
                    </button>
                </div>
            </div>


        </form>
    </div>
    <!-- 内容03：表格  -->
    <table class="layui-hide" id="accountTable" lay-filter="accountTable"></table>
    <!-- 内容04：表格中的按钮  -->
    <script type="text/html" id="tableButton">
        <a id="btnEdit" class="layui-btn  layui-btn-xs" lay-event="changepwd">
            <i class="fa fa-key" aria-hidden="true"></i>&nbsp; 修改密码
        </a>
        <a id="btnEdit" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">
            <i class="fa fa-edit" aria-hidden="true"></i> &nbsp;编辑
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
            <i class="fa fa-trash" aria-hidden="true"></i>&nbsp; 删除
        </a>
    </script>
    <!-- 内容05：弹出层用户添加和编辑的表单 -->
    <div class="layerArea" style="display: none; padding: 20px;">
        <form class="layui-form" id="layerForm" lay-filter="layerForm">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="loginId"><b>账号：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="loginid" id="loginid" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 626px">
                    <label class="layui-form-label" for="roles"><b>角色：</b></label>
                    <div class="layui-input-block">
                        <div id="roles" class="xm-select-demo"></div>
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="loginpwd"><b>密码：</b></label>
                    <div class="layui-input-inline">
                        <input type="password" name="loginpwd" id="loginpwd" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="reloginpwd"><b>确认密码：</b></label>
                    <div class="layui-input-inline">
                        <input type="password" name="reloginpwd" id="reloginpwd" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="name"><b>姓名：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="name" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="status"><b>状态：</b></label>
                    <div class="layui-input-inline">
                        <input type="checkbox" name="status" id="status" lay-skin="switch" lay-text="启用|禁用">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="mobile"><b>电话：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="mobile" id="mobile" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="email"><b>邮箱：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="email" id="email" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="create_date"><b>创建时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="create_date" id="create_date" class="layui-input"
                               style="background-color:#eaeaea;">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="last_login"><b>上次登陆：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="last_login" id="last_login" class="layui-input"
                               style="background-color:#eaeaea;">
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- 内容06：修改密码的弹出层 -->
    <div class="layerArea_Pass" style="display: none;padding: 20px;">
        <form class="layui-form" id="changePwdForm" lay-filter="changePwdForm">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label"><b>账号：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="ch_loginid" name="ch_loginid" class="layui-input"
                               style="background-color: #eaeaea">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label"><b>姓名：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="ch_name" name="ch_name" class="layui-input"
                               style="background-color: #eaeaea">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label"><b>密码：</b></label>
                    <div class="layui-input-inline">
                        <input type="password" id="ch_one_pwd" name="ch_one_pwd" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label"><b>确认密码：</b></label>
                    <div class="layui-input-inline">
                        <input type="password" id="ch_two_pwd" name="ch_two_pwd" class="layui-input">
                    </div>
                </div>
            </div>
        </form>
    </div>
{% endblock %}


<!-- JS -->
{% block js %}
    <!-- 引入 xm-select -->
    <script src="{% static 'plugin/layui/layui_exts/xm-select/xm-select.js' %}"></script>
    <script>
        // 定义一个全局变量Operation记录当前执行的是添加还是修改  1-添加 2-修改
        let Operation = 0;
        // 入口函数
        $(function () {
            // 页面的初始化
            initPage();
            // 初始化表格
            initTable();
            // 所有的按钮响应
            buttonClick();


        });

        // ============= 页面的初始化 =========
        function initPage() {
            layui.use(['form'], function () {
                let form = layui.form;
            })


        }

        // ============= 初始化表格 ============
        function initTable() {
            layui.use(['table', 'form'], function () {
                let table = layui.table;
                let form = layui.form;

                // 渲染表格
                table.render({
                    elem: '#accountTable'
                    , even: 'true'
                    , url: "{% url 'list_account' %}"
                    , method: 'post'
                    , where: {
                        // 传递查询条件
                        queryStr: $('#queryStr').val().trim(),
                        status: $('#status').val(),
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                    }
                    , cols: [[
                        {type: 'numbers', width: 60, title: '编号', align: 'center'}
                        , {field: 'name', width: 100, title: '姓名', align: 'center'}
                        , {field: 'loginid', width: 80, title: '账号', align: 'center'}
                        , {
                            field: 'status', width: 120, title: '状态', align: 'center',
                            templet: function (res) {
                                if (res.status) {
                                    // 选中
                                    return "<input type='checkbox' value='" + res.loginid + "' lay-filter='accountStatus' lay-skin='switch' lay-text='启用|禁用' checked>"

                                } else {
                                    // 未选中
                                    return "<input type='checkbox' value='" + res.loginid + "'  lay-filter='accountStatus' lay-skin='switch' lay-text='启用|禁用'>"
                                }
                            }
                        }
                        , {field: 'mobile', width: 120, title: '手机号码', align: 'center', sort: true}
                        , {field: 'email', title: '邮箱地址', align: 'center', sort: true}
                        , {field: 'create_date', width: 160, title: '创建时间', align: 'center', sort: true}
                        , {field: 'last_login', width: 160, title: '上次登陆时间', align: 'center', sort: true}
                        , {fixed: 'right', title: '操作', width: '20%', align: 'center', toolbar: '#tableButton'}
                    ]]
                    , page: true
                    , limit: 12
                    , limits: [12, 15, 20, 25, 30, 50, 75, 100]
                    , done: function (res, current, count) {
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'});
                    }

                });

                // 侦听表格的动作
                table.on('tool(accountTable)', function (obj) {
                    // 获取当前操作行的数据
                    let oneLineData = obj.data;
                    // 判断点击的操作类型
                    if (obj.event === 'edit') {
                        // ==== 编辑 ===
                        // 修改Operation
                        Operation = 2;
                        // 加载弹出层
                        loadLayer("编辑【登陆账号】", oneLineData);

                    } else if (obj.event === 'changepwd') {
                        loadChPwdLayer(oneLineData);
                    } else if (obj.event === 'del') {
                        deleteValue(oneLineData);
                    }
                });

                // 侦听表格中的switch的checkbox
                form.on('switch(accountStatus)', function (obj) {
                    $.ajax({
                        url: "{% url 'ch_status_account' %}",
                        method: 'post',
                        data: {
                            loginid: obj.value,
                            status: obj.elem.checked ? 1 : 0,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        },
                        dataType: 'json',
                        success: function (res) {
                            location.reload();
                        }
                    })
                })
            })
        }


        //============== 按钮响应 ================
        function buttonClick() {
            // == 查询 ==
            $('#btnQuery').on('click', function () {
                initTable();
            });
            // == 显示全部 ==
            $('#btnAll').on('click', function () {
                location.reload();
            });
            // == 添加 ==
            $('#btnAdd').on('click', function () {
                // 修改Operation值
                Operation = 1;
                loadLayer("添加【登陆账号】");
            })
        }

        //============== 展示弹出层 =============
        function loadLayer(title, value = "") {
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                // 展示弹出层
                layer.open({
                    type: 1,
                    title: "<b style='color:navy'>" + title + "</b>",
                    area: ['740px', '500px'],
                    btn: ['确定', '取消'],
                    content: $('.layerArea'),
                    offset: '10px',
                    resize: false,

                    // ======= 回调函数部分 ====
                    success: function (layero, index) {

                        // 初始化下拉角色
                        let role_select = xmSelect.render({
                            el: '#roles',
                            tips: '请选择角色',
                            filterable: true,
                            name: 'roles',
                            data: []
                        });
                        // 为下拉框获取值
                        $.ajax({
                            url: "{% url 'get_roles_all' %}",
                            method:'get',
                            dataType:'json',
                            async:false,
                            success: function (res) {
                                console.log(res);
                                role_select.update({
                                    data: res.data,
                                })
                            }
                        });
                        console.log(value.selected_role);
                        // 为当前用户选择所属的组
                        role_select.setValue(value.selected_role);

                        // 为弹出层表单赋值
                        form.val('layerForm', value);
                        // 赋值的时候清除密码和确认密码的value
                        $('#loginpwd, #reloginpwd').val("");

                        // 在修改的时候设置loginid无法修改
                        if (Operation === 2) {
                            $('#loginid').prop('readonly', true);
                        }
                        // 创建时间和修改时间改为readonly
                        $('#last_login, #create_date').prop('readonly', true);

                    },
                    yes: function (layero, index) {
                        // 定义一个要提交的url
                        let CommitURL = "{% url 'add_account' %}";
                        // 判断是否是修改
                        if (Operation === 2) {
                            CommitURL = "{% url 'edit_account' %}";
                        }
                        // 判断表单是否满足要求  -- 只有返回True才提交
                        if (checkFormCommit()) {
                            // 使用Ajax提交
                            $.ajax({
                                url: CommitURL,
                                method: 'post',
                                data: $('#layerForm').serialize(),
                                dataType: 'json',
                                success: function (res) {
                                    if (res.status) {
                                        location.reload();
                                    } else {
                                        layer.msg(res.error, {
                                            icon: 2,
                                            area: ['500px', '200px'],
                                            time: -1,
                                            btn: ['取消'],
                                        })
                                    }
                                }
                            })

                        }


                    },
                    end: function (layero, index) {

                        // 清空表单的赋值
                        form.val('layerForm', {
                            loginid: "",
                            name: "",
                            mobile: "",
                            email: "",
                            address: "",
                            create_date: "",
                            last_login: "",
                        });
                        // 把loginId的readonly取消
                        $('#loginid').prop('readonly', false);
                        // 清除表单所有的报错
                        $('.error_msg').empty();
                    }


                })
            })
        }

        // ============= 展示修改密码的弹出层 =====
        function loadChPwdLayer(value) {
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1,
                    title: "<b style='color:navy'>修改密码</b>",
                    area: ['420px', '400px'],
                    content: $('.layerArea_Pass'),
                    btn: ['确定', '取消'],
                    resize: false,

                    // =========== 回调函数 ==========
                    success: function (index, layero) {
                        // 填充Id和姓名
                        form.val('changePwdForm', {
                            ch_loginid: value.loginid,
                            ch_name: value.name,
                        });

                        // id和姓名无法修改
                        $('#changePwdForm').find('#ch_loginid, #ch_name').prop('readonly', true);
                    },
                    yes: function (index, layero) {

                        $.ajax({
                            url: "{% url 'chpwd_account' %}",
                            method: 'post',
                            data: {
                                loginid: $('#ch_loginid').val(),
                                loginpwd: $('#ch_one_pwd').val(),
                                csrfmiddlewaretoken: "{{ csrf_token }}",
                            },
                            success: function (res) {
                                if (res.status) {
                                    layer.msg('密码修改成功！');
                                    layer.close(index);
                                } else {
                                    layer.msg(res.error, {
                                        icon: 2,
                                        area: ['400px', '150px'],
                                        time: -1,
                                        btn: ['关闭']
                                    })
                                }
                            },

                        })
                    },
                    end: function (index, layero) {
                        // 清除信息
                        form.val('changePwdForm', {
                            ch_one_pwd: "",
                            ch_two_pwd: "",
                        })

                    }
                })
            })
        }

        //============== 检查表单的输入 ===========
        function checkFormCommit() {
            // 清除所有的错误
            $('.error_msg').empty();
            // 定义一个result --- 记录是否符合要求
            let flag = true;

            // 1. 校验登陆账号
            // 1.1 是否为4位的整数
            let loginid = $('#loginid').val();
            // 使用正则判断
            if (loginid.match(/^\d{4}$/) == null) {
                // 修改result
                flag = false;
                // 展示错误
                $('#loginid').next().text("登陆账号必须要是4位的整数！");
            }
            // 1.2 判断账号是否存在
            if (Operation === 1) {
                $.ajax({
                    url: "{% url 'is_exists_account' %}",
                    method: 'post',
                    data: {
                        loginid: loginid,
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    },
                    dataType: 'json',
                    async: false,  // 是否启用异步请求，默认是true
                    success: function (res) {
                        if (res.result) {
                            // 修改result
                            flag = false;
                            // 展示错误
                            $('#loginid').next().text("登陆账号已存在！");

                        }
                    }
                })
            }

            // 2.1 密码部分   A： 密码必须大于等于6  B： 两次密码一致
            let pwd = $('#loginpwd').val();
            if (pwd.length < 6 && Operation === 1) {
                // 修改result
                flag = false;
                // 展示错误
                $('#loginpwd').next().text("密码不能小于6位！");
            }
            let repwd = $('#reloginpwd').val();
            if (pwd != repwd && Operation === 1) {
                // 修改result
                flag = false;
                // 展示错误
                $('#reloginpwd').next().text("两次密码不一致！");
            }

            // 3。姓名 【2-5个汉字】
            let name = $('#name').val();
            if (name.match(/^[\u4E00-\u9FA5]{2,5}$/) == null) {
                // 修改result
                flag = false;
                // 展示错误
                $('#name').next().text("姓名必须2-5个汉字！");
            }

            // 4. 手机号码
            let mobile = $('#mobile').val();
            if (mobile.match(/^\d{11,12}$/) == null) {
                // 修改result
                flag = false;
                // 展示错误
                $('#mobile').next().text("电话号码必须是11-12的数字！");
            }
            // 5. 邮箱地址
            let email = $('#email').val();
            if (email.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/) == null) {
                // 修改result
                flag = false;
                // 展示错误
                $('#email').next().text("邮箱地址不符合要求！");
            }

            // 返回
            return flag;
        }

        // ================实现登录账号的删除 ==============
        function deleteValue(value) {
            layui.use(['layer'], function () {
                let layer = layui.layer;
                // 准备删除的确认文字
                let confirmStr = "请确定删除登陆账号【账号: " + value.loginid + "\t 姓名：" + value.name + "】信息吗？";
                // 跳出确认框
                layer.confirm(confirmStr, {
                    icon: 3,
                    title: '删除确认',
                    area: ['500px', '220px'],
                    time: -1,
                    btn: ['确定', '取消']
                }, function (index) {
                    // 使用Ajax删除
                    $.ajax({
                        url: "{% url 'del_account' %}",
                        method: 'post',
                        data: {
                            loginid: value.loginid,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        },
                        dataType: 'json',
                        success: function (res) {
                            if (res.status) {
                                location.reload();
                            } else {
                                layer.msg(res.error, {
                                    icon: 2,
                                    area: ['500px', '220px'],
                                    time: -1,
                                    btn: ['关闭'],
                                })
                            }
                        }
                    })
                })

            })


        }

    </script>
{% endblock %}